This example is for the SET constraints. The table in SQL can be created by $(D $(D sql CREATE TABLE Students ( Id INTEGER NOT NULL PRIMARY KEY, Name VARCHAR(55), Certificates SET(1 2 1 1 ); ))
1 import db_constraints; 2 3 class Student 4 { 5 private int _Id; 6 @PrimaryKeyColumn @NotNull 7 @property int Id() 8 { 9 return _Id; 10 } 11 @property void Id(int value) 12 { 13 setter(_Id, value); 14 } 15 private string _Name; 16 @property string Name() 17 { 18 return _Name; 19 } 20 @property void Name(string value) 21 { 22 setter(_Name, value); 23 } 24 private string _Certificates; 25 // Certificates can only have values that 26 // are among the set below. 27 @SetConstraint!("A1", "A2", "B1", "C1") 28 @property string Certificates() 29 { 30 return _Certificates; 31 } 32 @property void Certificates(string value) 33 { 34 setter(_Certificates, value); 35 } 36 this(int Id_, string Name_, string Certificates_) 37 { 38 this._Id = Id_; 39 this._Name = Name_; 40 this._Certificates = Certificates_; 41 initializeKeyedItem(); 42 } 43 44 mixin KeyedItem!(); 45 } 46 47 // A1 and B1 are both allowed in the set so no error is raise here 48 auto paul = new Student(1, "Paul", "A1,B1"); 49 // we can see paul's certificates are the same as they came in 50 assert(paul.Certificates == "A1,B1"); 51 52 // all of jane's certificates are acceptable but not in order 53 auto jane = new Student(2, "Jane", "A1,B1,A2"); 54 // the set constraint sorts the certificates for you 55 assert(jane.Certificates == "A1,A2,B1"); 56 57 // now lets try with some duplicates 58 jane.Certificates = "A1,A2,B1,A1"; 59 // the set constraint will also remove duplicates 60 assert(jane.Certificates == "A1,A2,B1"); 61 62 // if we enter in certificates that are not allowed we should expect an exception 63 import std.exception : assertThrown; 64 assertThrown!CheckConstraintException(new Student(3, "Mark", "A1,A2,D1,D2"));